const router = require('express').Router();
const Controller = require('../controller/user');

// 注册
router.post('/register', async (req, res) => {
    const { username, password } = reqBody;
    try {
        var token = await Controller.register(username, password);
        returnSuccess(res, 'Registration successful', token);
    } catch (error) {
        console.log(error);
        res.json({
            status: 502,
            message: 'Invalid credentials',
        });
    }
})

// 登录
router.post('/login', async (req, res) => {

    const { username, password } = req.body;
    try {
        var token = await Controller.login(username, password);
        returnSuccess(res, 'Login successful', token);
    } catch (error) {
        console.log(error);
        res.json({
            status: 503,
            message: 'Invalid credentials',
        });
    }
})

// 修改密码
router.post('/update', async (req, res) => {
    // console.log(req.body);
    const { username } = req.cookies.username;
    const { oldPassword, newPassword } = req.body;
    try{
        var newToken = await Controller.updatePassword(username, oldPassword, newPassword);
        returnSuccess(res, 'Password updated successfully', newToken);
    } catch (error) {
        console.log(error);
        res.json({
            status: 504,
            message: 'Invalid credentials',
        });
    }
})

function returnSuccess(res, message, token) {
    // 设置 Cookie 并发送响应
    res.cookie('authToken', token, {
        httpOnly: true, // 防止JavaScript访问该Cookie
        secure: false,   // 只通过HTTPS传输（生产环境中应启用）
        sameSite: 'strict', // 防止跨站请求伪造攻击
        maxAge: 7 * 24 * 60 * 60 * 1000  // Cookie有效期（毫秒），这里是7天
    });
    res.json({
        status: 200,
        message
    });
}

module.exports = router;
